package com.xaicode.learn.java.thread;

import java.util.concurrent.CyclicBarrier;

/**
 * @author Locker cjxia@isoftstone.com
 * @version 1.0
 */
public class TestCyclicBarrier {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(3, new TotalTask());
        BillTask billTask1 = new BillTask("111", barrier);
        BillTask billTask2 = new BillTask("222", barrier);
        BillTask billTask3 = new BillTask("333", barrier);
        billTask1.start();
        billTask2.start();
        billTask3.start();
        System.out.println("main thread end");
    }

    static class TotalTask extends Thread {
        @Override
        public void run() {
            System.out.println("全部子任务执行完，开始执行主任务");
        }
    }

    static class BillTask extends Thread {
        private String billName;
        private CyclicBarrier barrier;

        public BillTask(String billName, CyclicBarrier barrier) {
            this.billName = billName;
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                System.out.println("市区：" + billName + " 运算开始：");
                Thread.sleep(1000L);
                System.out.println("市区：" + billName + " 运算完成，等待中...");
                barrier.await();
                System.out.println("全部结束，市区 " + billName + " 才开始后面的工作");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
